package com.photoeditor.demo.ui.activity.subscribe;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.SkuDetails;
import com.billing.base.BillingManager;
import com.billing.base.SimpleBillingUpdateListener;
import com.billing.base.SkuWithType;
import com.billing.base.internal.SkuDetailsCacheManager;
import com.bumptech.glide.load.engine.Resource;
import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.TimeConstant;
import com.common.commercialize.sdk.CommercializeSDK;
import com.google.android.exoplayer2.C;
import com.photoeditor.R;
import com.photoeditor.demo.model.event.SubscribeFinishEvent;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpConstant;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.SVipConstant;
import com.photoeditor.demo.model.subscribe.manager.SVipController;
import com.photoeditor.demo.model.subscribe.manager.SkuManager;
import com.photoeditor.demo.model.subscribe.manager.VipStatisticUtil;
import com.photoeditor.demo.model.subscribe.strategy.SVipStrategyManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.HomeActivity;
import com.photoeditor.demo.ui.widget.RippleConstraintLayout;
import com.photoeditor.demo.ui.widget.SubscribePlayerView;
import com.photoeditor.demo.ui.widget.VideoForegroundView;
import com.photoeditor.demo.util.AndroidDevice;
import com.photoeditor.demo.util.AppFrontBackHelper;
import com.photoeditor.demo.util.FontUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.OnClick;

import static android.view.KeyEvent.KEYCODE_BACK;
import static com.photoeditor.demo.app.Global.PRIVACY_URL;
import static com.photoeditor.demo.app.Global.REFUND_URL;
import static com.photoeditor.demo.statistics.StatisticsConstant.ENTRANCE_VALUE_OPEN_APP;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_A;
import static com.photoeditor.demo.statistics.StatisticsConstant.MAIN_PAGE_TYPE_B;


/**
 * Created by cjh on 2020/2/4 .
 */
public class SubscribeFunctionsActivity extends BaseSubscribeVideoActivity implements ViewPager.OnPageChangeListener {

    public static boolean sSubscribeShow = false;
    public static boolean isFilter = false;//判断是不是滤镜跳转功能订阅页
    public static boolean isSticker = false;//判断是不是贴纸跳转功能订阅页
    public static String title;
    public static String equityTitles;
    public String getTitle;
    public String getEquityTitles;
    public static String entranceFunctions;


    @Bind(R.id.player_view)
    SubscribePlayerView mPlayerView;
    @Bind(R.id.image_subscribe)
    ImageView imageSubscribe;
    @Bind(R.id.video_foreground)
    VideoForegroundView mVideoForegroundView;
    @Bind(R.id.tv_feature_title)
    AppCompatTextView mTitleTextView;
    @Bind(R.id.video_banner_layout)
    ConstraintLayout videoBannerLayout;
    @Bind(R.id.tv_feature_equity_titles)
    AppCompatTextView mEquityTitleTextView;

    @Bind(R.id.tv_vip_bottom_tip)
    TextView mTvBottomTip;
    @Bind(R.id.iv_vip_btn_anim)
    ImageView mIvBtnAnim;

    @Bind(R.id.cancel)
    TextView mCancelTextView;

    private AnimationDrawable mDrawable;
    private int payColor;
    private TransitionDrawable transitionDrawable;
    private CycleGradientHandler mHandler;

    private String mPricePerMonMonthly;
    private String mPriceYearly;
    private String mFreeDaysMonthly;
    private String mFreeDaysYearly;

    private int mSkuType;

    private boolean mHasShowRetain;

    private boolean mStartMain;
    private boolean mHasLoadPrice;
    private Rect mPlayerViewRect;

    //视频播放开始时间和结束时间和视频id
    private static long startPosMs;
    private static long endPosMs;
    private static int videoId;

    private static String entranceFilterAndStickers;


    private int mCount;
    private List<View> mIndicators = new ArrayList<>();
    private int mLastPosition = 0;

    private boolean mFirstClick = true;


    private class CycleGradientHandler extends Handler{
        private WeakReference<TransitionDrawable> mRef;
        public CycleGradientHandler(TransitionDrawable transitionDrawable) {
            this.mRef = new WeakReference<>(transitionDrawable);
        }
        @Override
        public void handleMessage(Message msg) {
            TransitionDrawable transitionDrawable = mRef.get();
            super.handleMessage(msg);
            if (msg.what == 1) {
                //do something
                transitionDrawable.startTransition(1500);
            }
        }
    }

    public Timer timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            Message message = new Message();
            message.what = 1;
            mHandler.sendMessage(message);
        }
    };

    private SimpleBillingUpdateListener mDetailsResponseListener = new SimpleBillingUpdateListener() {
        @Override
        public void onSkuDetailsResponse(int i, List<SkuDetails> list) {
            if (list == null || list.isEmpty()) {
                return;
            }
            mHasLoadPrice = true;
            String skuMonth = SkuManager.getSkuInfoLast(SkuManager.TYPE_MONTHLY);
            String skuYear = SkuManager.getSkuInfoLast(SkuManager.TYPE_YEARLY);

            for (SkuDetails skuDetails : list) {
                if (TextUtils.equals(skuDetails.getSku(), skuMonth)) {
                    mPricePerMonMonthly = skuDetails.getPrice();
                } else if (TextUtils.equals(skuDetails.getSku(), skuYear)) {
                    mPriceYearly = skuDetails.getPrice();
                }
            }
            initPriceView();
        }
    };

    public static void startActivity(Activity activity, String entrance,String entranceStatistic, SVipController.OnSubscribeCloseListener listener, int requestCode, boolean startMain) {
        //换标题，权益文案和视频
        //老化
        if(entranceStatistic.equals(StatisticsConstant.ENTRANCE_VALUE_FILTER)){//滤镜
            if(SpUtils.obtain().getBoolean("isFunctionFilter", false)){//是点击主页功能卡片的滤镜的功能订阅页进来的
                entranceFunctions="filter";
            }else{//其他的滤镜素材页
                entranceFunctions="filterPage";
            }
            isFilter=true;
            title=activity.getString(R.string.tv_function_title_filter);
            equityTitles=activity.getString(R.string.tv_equity_titles_filter);
        }else if(entranceStatistic.equals(StatisticsConstant.ENTRANCE_VALUE_STICKER)){//贴纸
            SpUtils.obtain().save(SpConstant.IS_FUNCTION_STICKERS,true);
            entranceFunctions=entranceStatistic;
            isSticker=true;
            title=activity.getString(R.string.tv_function_title_sticker);
            equityTitles=activity.getString(R.string.tv_equity_titles_sticker);
        }else{
            entranceFunctions=entrance;
            switch (entrance) {
                case "aging":
                    title=activity.getString(R.string.tv_function_title_aging);
                    equityTitles=activity.getString(R.string.tv_equity_titles_aging);
                    break;
                case "gender":
                    title=activity.getString(R.string.tv_function_title_gender);
                    equityTitles=activity.getString(R.string.tv_equity_titles_gender);
                    break;
                case "past":
                    title=activity.getString(R.string.tv_function_title_past);
                    equityTitles=activity.getString(R.string.tv_equity_titles_past);
                    break;
                case "baby":
                    title=activity.getString(R.string.tv_function_title_baby);
                    equityTitles=activity.getString(R.string.tv_equity_titles_baby);
                    break;
                default:
                    break;
            }
        }
        SPDataManager.showTodayAllSubscribeMask();
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SHOW_VIPFUNSUB,
                StatisticsConstant.KEY_ENTRANCE, entranceFunctions);

        Intent intent = new Intent(ComponentContext.getContext(), SubscribeFunctionsActivity.class);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE, entrance);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE_FUNCTIONS, entranceFunctions);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE_STATISTIC, entranceStatistic);
        intent.putExtra(EXTRA_TYPE,"A");
        intent.putExtra(EXTRA_START_MAIN, startMain);
        intent.putExtra(EXTRA_IS_FUNCTION_SUBSCRIBE, true);

        activity.startActivityForResult(intent, requestCode);
        sOnSubscribeCloseListener = listener;
        sSubscribeShow = true;
    }

    public static void startActivity(String entrance, SVipController.OnSubscribeCloseListener listener) {
        Intent intent = new Intent(ComponentContext.getContext(), SubscribeFunctionsActivity.class);
        intent.putExtra(EXTRA_STATISTICS_ENTRANCE, entrance);
        intent.putExtra(EXTRA_TYPE,"A");
        ComponentContext.getContext().startActivity(intent);
        sOnSubscribeCloseListener = listener;
        sSubscribeShow = true;
    }

    @Override
    protected void initData() {
        super.initData();
        //设置标题和权益文案
        mTitleTextView.setText(getString(R.string.tv_function_title,title));
        mEquityTitleTextView.setText(getString(R.string.tv_equity_titles,equityTitles));
        if(isFilter){
            //隐藏视频，显示对应滤镜或者贴纸的图片
            videoBannerLayout.setVisibility(View.GONE);
            imageSubscribe.setVisibility(View.VISIBLE);
            imageSubscribe.setImageResource(R.drawable.transition_drawable_function_filter);
            transitionDrawable = (TransitionDrawable)imageSubscribe.getDrawable();
            mHandler = new CycleGradientHandler(transitionDrawable);
            //主线程中调用：
            timer.schedule(timerTask, 0, 5000);//延时0s，每隔5000毫秒执行一次run方法
            isFilter=false;
        }else if(isSticker){
            //隐藏视频，显示对应滤镜或者贴纸的图片
            videoBannerLayout.setVisibility(View.GONE);
            imageSubscribe.setVisibility(View.VISIBLE);
            imageSubscribe.setImageResource(R.drawable.transition_drawable_function_stickers);
            transitionDrawable = (TransitionDrawable)imageSubscribe.getDrawable();
            mHandler = new CycleGradientHandler(transitionDrawable);
            //主线程中调用：
            timer.schedule(timerTask, 0, 5000);//延时0s，每隔5000毫秒执行一次run方法
            isSticker=false;
        }
        mStartMain = getIntent().getBooleanExtra(EXTRA_START_MAIN, false);
        mHasShowRetain = false;
        mSkuType = SVipStrategyManager.getInstance().getFirstSubscribeType();

        mFreeDaysMonthly = SkuManager.getVipFreeDays(SkuManager.TYPE_MONTHLY);
        mFreeDaysYearly = SkuManager.getVipFreeDays(SkuManager.TYPE_YEARLY);

        String skuMonth = SkuManager.getSkuInfoLast(SkuManager.TYPE_MONTHLY);
        if (!TextUtils.isEmpty(skuMonth)) {
            SkuWithType skuWithType = new SkuWithType(skuMonth, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType);
            if (cacheSkuDetails != null) {
                String price = cacheSkuDetails.getPrice();
                if (!TextUtils.isEmpty(price)) {
                    mHasLoadPrice = true;
                    mPricePerMonMonthly = price;
                }
            }
        }

        String skuYear = SkuManager.getSkuInfoLast(SkuManager.TYPE_YEARLY);
        if (!TextUtils.isEmpty(skuYear)) {
            SkuWithType skuWithType = new SkuWithType(skuYear, BillingClient.SkuType.SUBS);
            SkuDetails cacheSkuDetails = SkuDetailsCacheManager.getInstance().getCacheSkuDetails(skuWithType);
            if (cacheSkuDetails != null) {
                String price = cacheSkuDetails.getPrice();
                if (!TextUtils.isEmpty(price)) {
                    mHasLoadPrice = true;
                    mPriceYearly = price;
                }
            }
        }

        BillingManager.getInstance().addBillingUpdatesListener(mDetailsResponseListener);
        initPriceView();
    }

    private void initPriceView() {
        mCancelTextView.setText(String.format(getResources().getString(R.string.vip_feature_tip),
                mFreeDaysMonthly));



        if (mSkuType == SkuManager.TYPE_MONTHLY) {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPricePerMonMonthly) ?
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly,
                            getResources().getText(R.string.vip_price_b_month)) :
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly, mPricePerMonMonthly));

            setCheckStatus(true);
        } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPriceYearly) ?
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly,
                            getResources().getText(R.string.vip_price_b_year)) :
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly, mPriceYearly));

            setCheckStatus(false);
        }

        if (SVipStrategyManager.getInstance().canShowBottomTipText(SVipConstant.VIP_ENTRANCE_IN_APP)) {
            mTvBottomTip.setVisibility(View.VISIBLE);
        } else {
            mTvBottomTip.setVisibility(View.GONE);
        }
    }

    private void setPrivacyUnderlineBuyUser(String privacyFull) {
        String privacy = getResources().getString(R.string.vip_privacy);
        int privacySIndex = privacyFull.indexOf(privacy);
        int privacyEIndex = privacySIndex + privacy.length();
        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
        try {
            builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
                }

            }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvBottomTip.setHighlightColor(getResources().getColor(R.color.transparent));
        mTvBottomTip.setLinkTextColor(mTvBottomTip.getCurrentTextColor());
        mTvBottomTip.setMovementMethod(LinkMovementMethod.getInstance());
        mTvBottomTip.setText(builder);
    }

    private void setPrivacyUnderline(String privacyFull) {
        String privacy = getResources().getString(R.string.vip_privacy);
        int privacySIndex = privacyFull.indexOf(privacy);
        int privacyEIndex = privacySIndex + privacy.length();
        String refund = getResources().getString(R.string.vip_cancel_refund);
        int refundSIndex = privacyFull.indexOf(refund);
        int refundEIndex = refundSIndex + refund.length();
        SpannableStringBuilder builder = new SpannableStringBuilder(privacyFull);
        try {
            builder.setSpan(new UnderlineSpan(), privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AndroidDevice.startWebView(ComponentContext.getContext(), PRIVACY_URL);
                }
            }, privacySIndex, privacyEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new UnderlineSpan(), refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.setSpan(new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    AndroidDevice.startWebView(ComponentContext.getContext(), REFUND_URL);
                }
            }, refundSIndex, refundEIndex, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        mTvBottomTip.setHighlightColor(getResources().getColor(R.color.transparent));
        //mTvBottomTip.setLinkTextColor(mTvBottomTip.getCurrentTextColor());
        payColor=SpUtils.obtain().getInt("payColor", 0xff3a3a87);
        mTvBottomTip.setLinkTextColor(payColor);
        mTvBottomTip.setMovementMethod(LinkMovementMethod.getInstance());
        mTvBottomTip.setText(builder);
    }

    @Override
    protected void initView() {
        ((RippleConstraintLayout) findViewById(R.id.layout_vip_continue)).setMask(R.drawable.bg_subscribe_mask);
        mDrawable = (AnimationDrawable) mIvBtnAnim.getDrawable();
        mDrawable.start();
        FontUtil.setCustomFontBlackItalic(mTitleTextView);
        initFirstEnter();
    }

    private boolean firstEnter = false;

    private void initFirstEnter() {
        if (SpUtils.obtain().getBoolean("first_enter", true)) {
            SpUtils.obtain().save("first_enter", false);
            firstEnter = true;
        }
        showVipClose();
    }

    private void showVipClose() {
        if (!firstEnter) {
            findViewById(R.id.iv_vip_close).setVisibility(View.VISIBLE);
            return;
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Animation animation = AnimationUtils.loadAnimation(SubscribeFunctionsActivity.this, R.anim.activity_open_enter);
                findViewById(R.id.iv_vip_close).setVisibility(View.VISIBLE);
                findViewById(R.id.iv_vip_close).startAnimation(animation);
            }
        }, 2000);
    }

    @Override
    protected int getContentLayoutId() {

        return R.layout.activity_subscribe_functions;

    }

    @Override
    protected boolean isPurchaseSuccess(List<Purchase> purchases) {
        boolean isMonthlyVip = false;
        boolean isYearlyVip = false;
        if (purchases != null) {
            for (Purchase purchase : purchases) {
                String sku;
                if (purchase != null && (sku = purchase.getSku()) != null) {
                    String[] monthlySkus = SkuManager.getSkuInfo(SkuManager.TYPE_MONTHLY);
                    String[] yearlySkus = SkuManager.getSkuInfo(SkuManager.TYPE_YEARLY);
                    for (String monthlySku : monthlySkus) {
                        if (TextUtils.equals(sku, monthlySku)) {
                            isMonthlyVip = true;
                        }
                    }
                    if (!isMonthlyVip) {
                        for (String yearlySku : yearlySkus) {
                            if (TextUtils.equals(sku, yearlySku)) {
                                isYearlyVip = true;
                            }
                        }
                    }
                }
            }
        }

        return isMonthlyVip || isYearlyVip;
    }

    @Override
    protected void onPurchaseSuccess() {

        //只是针对测试的
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUCC_VIPFUNSUB,
                StatisticsConstant.KEY_ENTRANCE, entranceFunctions,
                StatisticsConstant.KEY_SKU, sku);

    }

    @Override
    protected void onPurchaseFailUserCancel() {
        super.onPurchaseFailUserCancel();
        if (!TextUtils.equals(mStatisticsEntrance, ENTRANCE_VALUE_OPEN_APP)) {

        } else if (mHasShowRetain || !SVipController.showRetainDialog(this, mStatisticsEntrance, 111)) {

        } else {
            mHasShowRetain = true;
            mVisible = false;
        }

    }

    /**
     * 页面
     *
     * @return
     */
    @Override
    public String getStatisticPageStr() {

        return StatisticsConstant.EVENT_MAIN_SUB;
    }

    @Override
    public String getSubscribeTypeStr() {
        return MAIN_PAGE_TYPE_A;
    }

    @Override
    public boolean statisticSubPageShowAndClick() {
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDrawable != null) {
            mDrawable.start();
        }
        if (!SVipStrategyManager.hasStatisticReopen()
                && System.currentTimeMillis() - CommercializeSDK.getInstance().getFirstInstallTime() < TimeConstant.ONE_DAY
                && SVipStrategyManager.hasLeaveFromSub()
                && !SVipStrategyManager.hasShowMainAfterSub()) {
            //在首次展示订阅页面后未进入首页即退出应用，在当天再次进入应用的用户
            SVipStrategyManager.setHasStatisticReopen();
            VipStatisticUtil.statisticLeaveIn();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDrawable != null) {
            mDrawable.stop();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (AppFrontBackHelper.getInstant().isAppBackground()) {
            SVipStrategyManager.setHasLeaveFromSub();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSubscribeFinishEvent(SubscribeFinishEvent event) {
        finish();
        statisticBack(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 111 && resultCode == RESULT_OK) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                    statisticBack(false);
                }
            }, 250);

        }
    }

    @Override
    public void onBackPressed() {
        if (SpUtils.obtain().getBoolean("first_enter", true)) {
            SpUtils.obtain().save("first_enter", false);
        } else {
            onBackClick();
            return;
        }
    }

    @OnClick(R.id.iv_vip_close)
    void onBackClick() {
        if (!TextUtils.equals(mStatisticsEntrance, ENTRANCE_VALUE_OPEN_APP)) {
            finish();
            statisticBack(false);
        } else if (mHasShowRetain || !SVipController.showRetainDialog(this, mStatisticsEntrance, 111)) {
            finish();
            statisticBack(false);
        } else {
            mHasShowRetain = true;
            mVisible = false;
            statisticCloseClick();
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        if (mHasShowRetain) {
            mVisible = false;
        }
    }

    void purchaseMonthly() {
        String[] normalSkus = SkuManager.getSkuInfo(SkuManager.TYPE_MONTHLY);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        subscribe(normalSkus[normalSkus.length - 1],
                StatisticsConstant.SUB_PACK_VALUE_MONTHLY);

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_BTN_CLICK,
                StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_MONTH,
                StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
                StatisticsConstant.KEY_AB_TYPE,StatisticsConstant.VALUE_A,
                StatisticsConstant.KEY_SKU,sku);
    }

    void purchaseYearly() {
        String[] normalSkus = SkuManager.getSkuInfo(SkuManager.TYPE_YEARLY);
        if (normalSkus == null || normalSkus.length == 0 || TextUtils.isEmpty(normalSkus[normalSkus.length - 1])) {
            return;
        }
        subscribe(normalSkus[normalSkus.length - 1],
                StatisticsConstant.SUB_PACK_VALUE_ANNUAL);

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SUB_BTN_CLICK,
                StatisticsConstant.KEY_SUB_PACK, StatisticsConstant.VALUE_SUB_PACK_YEAR,
                StatisticsConstant.KEY_ENTER_SUB, mStatisticsEntrance,
                StatisticsConstant.KEY_AB_TYPE,StatisticsConstant.VALUE_A,
                StatisticsConstant.KEY_SKU,sku);

    }

    @OnClick({R.id.layout_vip_continue})
    void onSubscribeClick() {
        //订阅年费
        purchaseYearly();

        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_CLICK_VIPFUNSUB,
                StatisticsConstant.KEY_ENTRANCE, entranceFunctions,
                StatisticsConstant.KEY_SKU,sku);
    }

    private void setCheckStatus(boolean first) {

        if (first) {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPricePerMonMonthly) ?
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly,
                            getResources().getText(R.string.vip_price_b_month)) :
                    String.format(getResources().getString(R.string.vip_privacy_month), mFreeDaysMonthly, mPricePerMonMonthly));

        } else {
            mTvBottomTip.setGravity(Gravity.LEFT);
            setPrivacyUnderline(TextUtils.isEmpty(mPriceYearly) ?
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly,
                            getResources().getText(R.string.vip_price_b_year)) :
                    String.format(getResources().getString(R.string.vip_privacy_year), mFreeDaysYearly, mPriceYearly));
        }
    }

    @Override
    protected void onDestroy() {
        sSubscribeShow = false;
        super.onDestroy();
        BillingManager.getInstance().removeBillingUpdatesListener(mDetailsResponseListener);

        if(mHandler!=null){
            mHandler.removeMessages(1);
        }
    }

    @Override
    protected SubscribePlayerView getPlayerView() {
        return mPlayerView;
    }

    @Override
    protected int getVideoResId() {
        return videoId;
    }

    @Override
    protected int[] getSrcVideoSize() {
        return new int[] {1080, 900};
    }

    @Override
    protected long[] getVideoStartAndEndPosMs() {
        long startPosMs = 0L;
        long endPosMs = 19000L;
        return new long[] {startPosMs, endPosMs};
    }

    @Override
    protected Rect getPlayerPosition() {
        if (mPlayerViewRect == null) {
            int left = 0;
            int top = 0;
            int width = DeviceUtils.getScreenWidthPx();
            int[] videoSize = getSrcVideoSize();
            int height = width * videoSize[1] / videoSize[0];
            mPlayerViewRect = new Rect(left, top, left + width, top + height);
        }

        return mPlayerViewRect;
    }

    @Override
    protected View getVideoForegroundView(int imageId) {
        mVideoForegroundView.setImageResId(imageId);
        return mVideoForegroundView;
    }

    @Override
    public void finish() {
        checkToStartMain();
        setResult(RESULT_OK);
        super.finish();
    }

    private void checkToStartMain() {
        if (mStartMain) {
            Intent i = new Intent(this, HomeActivity.class);
            startActivity(i);
            overridePendingTransition(R.anim.activity_no_animation, R.anim.activity_close_exit);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK && firstEnter) {
            return false;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KEYCODE_BACK && firstEnter) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mIndicators.get((mLastPosition + mCount) % mCount)
                .setBackground(getResources().getDrawable(R.drawable.indicator_grey));
        mIndicators.get((position + mCount) % mCount)
                .setBackground(getResources().getDrawable(R.drawable.indicator_white));
        mLastPosition = position;

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
